package org.rambadger.command.validation;

import org.apache.log4j.Logger;
import org.axonframework.commandhandling.interceptors.JSR303ViolationException;

import javax.validation.ConstraintViolation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.Set;

public class ValidationExceptionMapper implements ExceptionMapper<JSR303ViolationException> {
    private static Logger log = Logger.getLogger(ValidationExceptionMapper.class);
    @Override
    public Response toResponse(JSR303ViolationException exception) {
        StringBuilder acc = new StringBuilder();
        Set<ConstraintViolation<Object>> violations = exception.getViolations();
        for (ConstraintViolation<Object> violation : violations) {
            String message = String.format("on '%s': %s", violation.getPropertyPath(), violation.getMessage());
            log.warn(message);
            acc.append(message).append("\n");
        }

        return Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN_TYPE).entity(acc.toString()).build();
    }
}
